/**
  ******************************************************************************
  * @file    dev_key.c
  * @author  Yun
  * @version V1.0.0
  * @date    2025-02-12
  * @brief   按键设备驱动模块实现
  * @license EULA (End User License Agreement)
  *          Copyright (c) 2025 星瑜科技自动化 Co., Ltd. All rights reserved.
  ******************************************************************************
  */

/*---------------------- Includes ----------------------*/
#include "dev_button.h"

/*---------------------- 全局变量定义 ----------------------*/
/*!< 按键设备链表头指针 */
Dev_Button_Cfg_TypeDef* stDevButtonCfgNodeHead = NULL;

/*---------------------- 函数实现 ----------------------*/
/**
  * @brief  按键设备注册函数
  */
uint8_t Dev_Button_Register(Dev_Button_Cfg_TypeDef* pstDevButtonCfg,
                         void* pHwCfg,
                         Gpio_Interface_TypeDef* pstGpioInterface)
{
    /* 参数有效性检查 */
    if (!pstDevButtonCfg || !pHwCfg || !pstGpioInterface)
        return DEV_ERROR;

    DEV_UN_INIT(pstDevButtonCfg);

    /* 配置设备参数 */
    pstDevButtonCfg->pHwCfg = pHwCfg;
    pstDevButtonCfg->pstGpioInterface = pstGpioInterface;
    pstDevButtonCfg->u8CurState = !pstDevButtonCfg->u8ActState;

    /* 链表头部插入 */
    pstDevButtonCfg->pstNext = stDevButtonCfgNodeHead;
    stDevButtonCfgNodeHead = pstDevButtonCfg;

    /* 执行硬件初始化 */
    CHECK_DEV_STATUS(pstDevButtonCfg->pstGpioInterface->Init(pstDevButtonCfg->pHwCfg));

    DEV_INIT(pstDevButtonCfg);

    return DEV_OK;
}

/**
  * @brief  按键状态扫描函数
  */
void Dev_Button_Monitor(void* pArgs)
{
    (void)pArgs;
    Dev_Button_Cfg_TypeDef* pstCurrent = stDevButtonCfgNodeHead;

    while (pstCurrent != NULL)
    {
        if(pstCurrent->u8InitState != DEV_IS_INIT ||
           pstCurrent->u8RunState != DEV_IDLE) {
            pstCurrent = pstCurrent->pstNext;
            continue;
        }

        uint8_t u8ReadState = 0;

        DEV_BUSY(pstCurrent);

        /* 读取当前物理状态 */
        if(pstCurrent->pstGpioInterface->Read(pstCurrent->pHwCfg, &u8ReadState) != DEV_OK) continue;

        /* 状态变化检测 */
        if (u8ReadState != pstCurrent->u8CurState)
        {
            /* 触发事件逻辑 */
            if ((u8ReadState == pstCurrent->u8ActState) &&
                (pstCurrent->u8CurState != pstCurrent->u8ActState))
            {
                /* 按下事件 */
                DEV_PUSH_EVENT(EVENT_DEV_KEY_PRESSED, pstCurrent, pstCurrent);
            }
            else if ((u8ReadState != pstCurrent->u8ActState) &&
                     (pstCurrent->u8CurState == pstCurrent->u8ActState)) {
                /* 释放事件 */
                DEV_PUSH_EVENT(EVENT_DEV_KEY_RELEASED, pstCurrent, pstCurrent);
            }
            /* 更新当前状态 */
            pstCurrent->u8CurState = u8ReadState;
        }

        pstCurrent = pstCurrent->pstNext;
    }
}

/************************ (C) COPYRIGHT 星瑜科技自动化 *****END OF FILE****/
